package com.youboy.oauth.verifier;

import java.security.SecureRandom;
import java.util.Random;

public class RandomOAuthTokenVerifierService implements OAuthTokenVerifierService {

	private static final char[] DEFAULT_CODEC = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();

	private Random random = new SecureRandom();
	private int verifierLengthBytes = 8;

	@Override
	public String createVerifier() {
		byte[] verifierBytes = new byte[getVerifierLengthBytes()];
		getRandom().nextBytes(verifierBytes);
		return getVerifierString(verifierBytes);
	}

	/**
	 * Convert these random bytes to a verifier string. The length of the byte array can be
	 * {@link #setVerifierLengthBytes(int) configured}. Default implementation mods the bytes to fit into the ASCII
	 * letters 1-9, A-Z, a-z .
	 * 
	 * @param verifierBytes
	 *            The bytes.
	 * @return The string.
	 */
	protected String getVerifierString(byte[] verifierBytes) {
		char[] chars = new char[verifierBytes.length];
		for (int i = 0; i < verifierBytes.length; i++) {
			chars[i] = DEFAULT_CODEC[((verifierBytes[i] & 0xFF) % DEFAULT_CODEC.length)];
		}
		return new String(chars);
	}

	public Random getRandom() {
		return random;
	}

	public void setRandom(Random random) {
		this.random = random;
	}

	public int getVerifierLengthBytes() {
		return verifierLengthBytes;
	}

	public void setVerifierLengthBytes(int verifierLengthBytes) {
		this.verifierLengthBytes = verifierLengthBytes;
	}
}
